package de.tum.in.eist.poll.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

import de.tum.in.eist.poll.shared.Lecturer;
import de.tum.in.eist.poll.shared.UserNotFoundException;

/***
 * view for the lecturer to login
 */
public class LecturerLoginView {
	static void paint() {
		if(Poll.lecturer != null){
			History.newItem("viewResults");
			return;
		}
		RootPanel.get("logo").removeStyleName("logo-small");
		final TextBox loginBox = new TextBox();
		loginBox.addStyleName("loginBox");
		loginBox.getElement().setAttribute("placeholder", "Login");
		final PasswordTextBox passBox = new PasswordTextBox();
		passBox.addStyleName("passBox");
		passBox.getElement().setAttribute("placeholder", "Password");
		final Button submitButton = new Button("Login");
		class LoginHandler implements ClickHandler, KeyUpHandler {
			public void onClick(ClickEvent event) {
				authToServer();
			}
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					authToServer();
				}
			}
			public void authToServer() {
				final String login = loginBox.getText();
				final String pass = passBox.getText();
				loginBox.setText("");
				passBox.setText("");
				loginBox.setFocus(false);
				passBox.setFocus(false);
				loginBox.getElement().setAttribute("placeholder", "Logging in...");
				
				try {
					Poll.authService.authenticateLecturer(login, pass, new AsyncCallback<Lecturer>() {
						public void onFailure(Throwable caught) {
							loginBox.setText("");
							passBox.setText("");
							loginBox.setFocus(false);
							passBox.setFocus(false);
							loginBox.getElement().setAttribute("placeholder", "Network-Error");
						}
						public void onSuccess(Lecturer result) {
							Poll.lecturer = result;
							History.newItem("viewResults");
						}
					});
				} catch (de.tum.in.eist.poll.shared.exceptions.UserNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		LoginHandler lh = new LoginHandler();
		loginBox.addKeyUpHandler(lh);
		passBox.addKeyUpHandler(lh);
		submitButton.addClickHandler(lh);
		RootPanel.get("container").add(loginBox);
		RootPanel.get("container").add(passBox);
		RootPanel.get("container").add(submitButton);
	}
}
